package com.photoeditor.demo.ui.activity.face;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.android.gl.renderer.ISurfaceRenderer;
import com.android.gl.view.SurfaceView;
import com.android.gpuimage.AdjustGPUImageView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DebugUtil;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.common.commercialize.reward.RewardAdManager;
import com.common.commercialize.sdk.CommercializeSDK;
import com.common.commercialize.utils.TaskRunnable;
import com.google.firebase.ml.vision.face.FirebaseVisionFace;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.photoeditor.R;
import com.photoeditor.demo.ad.AdKeyConstant;
import com.photoeditor.demo.ad.MainReturnAdProvider;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.model.bean.BabyInputBean;
import com.photoeditor.demo.model.bean.face.BaseFaceResultBean;
import com.photoeditor.demo.model.bean.face.CommonFaceBean;
import com.photoeditor.demo.model.bean.face.FaceDetectBeanV4;
import com.photoeditor.demo.model.bean.face.FaceAgingFaceBean;
import com.photoeditor.demo.model.bean.face.FaceAgingResultBean;
import com.photoeditor.demo.model.event.AgeSuccessEvent;
import com.photoeditor.demo.model.event.FeedBackEvent;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.event.ReachGPEvent;
import com.photoeditor.demo.model.event.SubscribeSuccessEvent;
import com.photoeditor.demo.model.event.VipMaskIsShowEvent;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.face.report.reportlogic.BaseReportLogic;
import com.photoeditor.demo.model.face.report.reportlogic.ExoticReportLogic;
import com.photoeditor.demo.model.face.report.reportlogic.FutureBabyReportLogic;
import com.photoeditor.demo.model.face.report.reportlogic.GenderSwitchReportLogic;
import com.photoeditor.demo.model.face.report.reportlogic.OneTimeVipHelper;
import com.photoeditor.demo.model.face.report.reportlogic.FaceAgingReportLogic;
import com.photoeditor.demo.model.face.report.reportlogic.PastLifeReportLogic;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.mlkit.ImageFaceDetector;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.share.ShareImageDialogHelp;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.VipStatisticUtil;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.BabyMainActivity;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.HomeActivity;
import com.photoeditor.demo.ui.activity.edit.ImagePreviewActivity;
import com.photoeditor.demo.ui.dialog.DialogShow;
import com.photoeditor.demo.ui.dialog.DialogStatistic;
import com.photoeditor.demo.ui.dialog.IAdVideoDialogListener;
import com.photoeditor.demo.ui.dialog.IDialog;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.widget.face.VerticalScrollView;
import com.photoeditor.demo.ui.widget.oldify.OldifyDecorationContainer;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.photoeditor.demo.util.AppFrontBackHelper;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.DisplayUtils;
import com.photoeditor.demo.util.NetworkUtils;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.folder.FolderHelper;
import com.photoeditor.demo.util.gl.My3DRenderer;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_BABYPREDICT;
import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_EXOTIC;
import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH;
import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_FACE_AGING;
import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_PAST_LIFE;
import static com.photoeditor.demo.model.face.ErrorType.RESULT_OTHER;
import static com.photoeditor.demo.model.face.ErrorType.RESULT_PARSE_IMG_ERROR;
import static com.photoeditor.demo.model.face.ErrorType.RESULT_SUCCESS;
import static com.photoeditor.demo.model.face.ErrorType.getErrorTypeByReturnType;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_EXOTIC_BLEND;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_FUTURE_BABY;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_GENDER_SWITCH;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_FACE_AGING;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_PAST_LIFE;
import static com.photoeditor.demo.model.face.FaceConstant.PATH_PHOTO;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.model.preference.SpUtils.ISFROMBUTTON;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_ALBUMCLICK;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_CLICK;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_CLOSE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_OTHER_CLINET;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_OTHER_ONLINE_ERROR;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_SHOW;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VIP_PAGE_RESULTPAGE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_FACE_FUN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_AGING;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_BABY;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_GENDER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_PAST;
import static com.photoeditor.demo.util.BitmapUtil.getOptimizeBmpBase64;
import static com.photoeditor.demo.util.face.FaceUtil.getDetectFaceType;

/**
 * 所有脸部分析报告页面容器
 * Created by @author winn on 2018/10/29.
 */

public class FaceLogicActivity extends XActivity implements BaseReportLogic.OnEventListener,
        View.OnClickListener, ImageFaceDetector.OnImageFaceDetectListener {
    private static final String TAG = FaceLogicActivity.class.getSimpleName();
    private final static String EXTRA_KEY_ACTION = "EXTRA_KEY_ACTION";
    private final static String EXTRA_KEY_IMAGE_YOUS = "EXTRA_KEY_IMAGE_YOUS";
    private static final String EXTRA_KEY_BABY_INFO_BEAN = "EXTRA_KEY_BABY_INFO_BEAN";

    public static final int REQUEST_CODE_CHOOSE_PHOTO_YOU = 120;

    @Bind(R.id.rl_content)
    RelativeLayout mScreenView;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.icon_back)
    ImageView mBackView;
    @Bind(R.id.render_parent)
    RelativeLayout mRenderParent;
    @Bind(R.id.layout_top_panel)
    RelativeLayout mTitleBar;
    @Bind(R.id.scroll_view)
    VerticalScrollView mScrollView;
    @Bind(R.id.empty_view)
    View mEmptyView;
    @Bind(R.id.loading_animation_view)
    LottieAnimationView mLoadingView;
    @Bind(R.id.oldify_decoration_container)
    OldifyDecorationContainer mDecorationView;
    @Bind(R.id.switch_image)
    ImageView mSwitchImage;

    private FrameLayout mReportViewContainer;
    private SurfaceView mModelView;
    private AdjustGPUImageView mGPUImageView;
    private ISurfaceRenderer mRender;

    private static boolean isfromButton =false;

    private int mWhere = DialogStatistic.RateWhere.TYPE_ID_FACE_AGING;

    //    private String mImgSavePath = FileUtil.getExternalCacheDir(ComponentContext.getContext(), "Albums", true);
    private String mImgSavePath = FolderHelper.getOrCreateSaveLocation();
    private BaseFaceResultBean mBaseFaceResultBean;
    private BaseReportLogic mReportLogic;
    private String mStatisticRetain;
    private ShareImageDialogHelp mShareImageDialogHelp;
    private ImageFaceDetector mImageFaceDetector;
    //    private int mSubscribePageId;
    private boolean isVipBefore;
    private AnimationDrawable mDrawable;

    private String mAction;
    private int mActionType;
    private String[] mImageYous;
    private Bitmap mImgYou;
    private boolean isModel;
    private boolean mIsDestroy;

    private int mScanResultType;

    public static int degree = 0;

    String picSource = "known";
    private long timeCount;

    private MainReturnAdProvider mMainReturnAdProvider;


    /**
     * @param context
     * @param action  功能
     * @param from    统计用
     * @param imgYous 包含本地路径，若路径有多个，第一个是你的照片，第二个是partner(rival)的照片
     */
    public static void showReportActivity(Activity context, String action,
                                          int from, String... imgYous) {
        Intent intent = new Intent(context, FaceLogicActivity.class);
        intent.putExtra(EXTRA_KEY_ACTION, action);
        intent.putExtra(EXTRA_KEY_IMAGE_YOUS, imgYous);
        intent.putExtra(FaceConstant.EXTRA_FROM, from);
        context.startActivity(intent);
    }

    public static void showReportActivity(Activity context, String action,
                                          int from, BabyInputBean babyInputBean, String... imgYous) {
        Intent intent = new Intent(context, FaceLogicActivity.class);
        intent.putExtra(EXTRA_KEY_ACTION, action);
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_KEY_BABY_INFO_BEAN, babyInputBean);
        intent.putExtra("bundle", bundle);
        intent.putExtra(EXTRA_KEY_IMAGE_YOUS, imgYous);
        intent.putExtra(FaceConstant.EXTRA_FROM, from);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        EventBus.getDefault().register(this);
        initData();
        switch (getIntent().getIntExtra(FaceConstant.EXTRA_FROM, 0)) {
            case 0:
                picSource = "model";
                break;
            case 1:
                picSource = "album";
                break;
            case 2:
                picSource = "camera";
                break;
        }
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource);
        if (!AppVipManager.isVip() || SPDataManager.getAdOneTimeVip()) {
            //非vip用户才加载广告 或者是一次vip
            initAd();

            mMainReturnAdProvider = new MainReturnAdProvider(this, mReportLogic.getFeatureType());
            mMainReturnAdProvider.loadAd();
        }
        if (/*mBaseFaceResultBean == null || mScanInfo == null || */mReportLogic == null) {
            finish();
            return;
        }
        initView();
        mActionType = getDetectFaceType(mAction);
        SVipStrategyManager.addUsedFeature(SVipConstant.getAliasByFunType(mActionType));
//        checkVipView(true);
        checkRate();

        process();

        //展示结果次数自加一
        SPDataManager.addComeToResultPageCount();
        SPDataManager.comeIn();

        timeCount = System.currentTimeMillis();

        degree = 0;
    }

    //跳转功能订阅页
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTurnToFunctionSubscribeEvent(VipMaskIsShowEvent event) {
        if (!AppVipManager.isVip() && !isModel) { //非订阅非model
            if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
                DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                        "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
                showSubscribeDialog(true);
            } else {
                DLog.d("wLog", "若是当天第3次及之后进入模糊页，则直接在模糊页显示激励视频按钮，" +
                        "并不主动跳转主订阅页；");
            }
        }
    }

        private void checkRate() {
        int funcType = mActionType;
        String type = SPDataManager.getUseFuncType(funcType);
        if (type == null || type.equals(""))
            return;
        SPDataManager.addUseFunTypeToday(type);
        //进入星座tab查看了1组运势，并且下一个必須使用功能是免费功能，所以這裏清空
        SPDataManager.clearUseHoroscopeAfterUseFree();
    }

    private void initData() {
        if (!AppVipManager.isVip()) {
            SPDataManager.showTodayNorStickersSubscribeMask();
        }
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        mAction = intent.getStringExtra(EXTRA_KEY_ACTION);
        mImageYous = intent.getStringArrayExtra(EXTRA_KEY_IMAGE_YOUS);

        if (mImageYous == null || mImageYous.length == 0) {
            finish();
            return;
        }
        isModel = FaceConstant.isModel(mImageYous[0]);
        if (isModel) {
            mImgYou = APKAssertImageLoader.with(getResources()).load(mImageYous[0]).get();
        } else {
            mImgYou = ImageHelper.getBitmapFromPath(mImageYous[0]);
        }
        switch (mAction) {
            case ACTION_FACE_AGING:
                mReportLogic = new FaceAgingReportLogic(mImageYous[0]);
                ((FaceAgingReportLogic) mReportLogic).setActivity(this);
                mStatisticRetain = StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_AGE_RETAIN;
                mWhere = DialogStatistic.RateWhere.TYPE_ID_FACE_AGING;
                break;
            case ACTION_EXOTIC_BLEND:
//                mReportLogic = new ExoticReportLogic((FaceDetectBeanV4) mBaseFaceResultBean, null);
//                ((ExoticReportLogic) mReportLogic).setActivity(this);
//                mStatisticRetain = StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_EXTOTIC_RETAIN;
//                mWhere = 4;
                //TODO：需修改逻辑，适配换脸逻辑
                finish();
                break;
            case ACTION_GENDER_SWITCH:
                mReportLogic = new GenderSwitchReportLogic(mImageYous[0]);
                ((GenderSwitchReportLogic) mReportLogic).setActivity(this);
                mStatisticRetain = StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_GENDER_SWITCH_RETAIN;
                mWhere = DialogStatistic.RateWhere.TYPE_ID_GENDER_SWAP;
                break;
            case ACTION_PAST_LIFE:
                mReportLogic = new PastLifeReportLogic(mImageYous[0]);
                ((PastLifeReportLogic) mReportLogic).setActivity(this);
                mStatisticRetain = StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_PAST_LIFE_RETAIN;
                mWhere = DialogStatistic.RateWhere.TYPE_ID_PAST_LIFE;
                break;
            case ACTION_FUTURE_BABY:
                mReportLogic = new FutureBabyReportLogic(mImageYous[0], mImageYous[1]);
                ((FutureBabyReportLogic)mReportLogic).setActivity(this);
                Bundle bundle = intent.getBundleExtra("bundle");
                if (bundle != null) {
                    BabyInputBean babyInputBean = (BabyInputBean)bundle.getSerializable(EXTRA_KEY_BABY_INFO_BEAN);
                    ((FutureBabyReportLogic) mReportLogic).setBabyInputBean(babyInputBean);
                }
                mStatisticRetain = StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_FUTURE_BABY;
                mWhere = DialogStatistic.RateWhere.TYPE_ID_FUTURE_BABY;
                break;
            default:
                break;
        }

        if (mReportLogic != null) {
            mReportLogic.setOnEventListener(this);
        }
    }

    private void process() {
        if (isModel) {
            return;
        }
        //年龄扫描是免费功能
        requestData();
        if (!TextUtils.equals(mAction, ACTION_FUTURE_BABY)) {
            startLoadingAnimation();
        }
    }

    private void requestData() {
        switch (mAction) {

            case ACTION_FACE_AGING:
//                if (FaceAgingReportLogic.isVersionBelowKitKat()) {
//                getDetectSingleImgTask().execute();
//                } else {
                //do nothing
//                }
//                detectFace(-1, null);
                getDetectSingleImgTask().execute();
                break;
            case ACTION_EXOTIC_BLEND:
                getDetectSingleImgTask().execute();
                break;
            case ACTION_GENDER_SWITCH:
                getDetectSingleImgTask().execute();
                break;
            case ACTION_PAST_LIFE:
                getDetectSingleImgTask().execute();
                break;
            default:
                break;
        }
    }

    private void initView() {
        setContentView(R.layout.activity_face_logic);
        ButterKnife.bind(this);
        mReportViewContainer = findViewById(R.id.report_container);
        View reportView = mReportLogic.getReportView(mReportViewContainer);
        if (reportView != null) {
            mReportViewContainer.addView(reportView, 0,
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            initSurfaceView();
        }
        initToolBar();

        findViewById(R.id.iv_save).setOnClickListener(this);
        mEmptyView.setOnClickListener(this);

        mReportLogic.onPageShow();

        if (mReportLogic.titleBarWithoutBg()) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.transparent));
        }

        if (mReportLogic instanceof FaceAgingReportLogic) {
            ((FaceAgingReportLogic) mReportLogic).recoverLastChoosen();
        }
        if (mReportLogic instanceof PastLifeReportLogic) {
            mSwitchImage.setVisibility(View.VISIBLE);
            mSwitchImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    enterGallery();
                }
            });
        }
        if (mReportLogic instanceof FutureBabyReportLogic) {
            mTitleBar.setVisibility(View.GONE);
        }
    }

    private void initToolBar() {
        mTvTitle.setText(mReportLogic.getReportTitleResId());

        mBackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        ImmersionBar.with(this)
                .transparentStatusBar()
                .init();

    }

    private void initSurfaceView() {
        if (TextUtils.equals(mAction, ACTION_FACE_AGING)) {
            mModelView = findViewById(R.id.model_view);
            mModelView.setTransparent(true);
            mRender = new My3DRenderer(FaceLogicActivity.this);
            mModelView.setSurfaceRenderer(mRender);

            mGPUImageView = findViewById(R.id.gpu_image_view);

            mGPUImageView.setVisibility(View.VISIBLE);
            mDecorationView.setVisibility(View.VISIBLE);

            if (AppVipManager.isVip()) {
//                ((AgeCameraReportLogic) mReportLogic).showLoadingView(true);
            }
        }
    }

    private void startLoadingAnimation() {
        DLog.d("lLog", "activity startLoadingAnimation()");
        if (!isLoadingAnimationShow()) {
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
            showEmptyViewCount++;
            mEmptyView.setVisibility(View.VISIBLE);
        }
    }

    public int showEmptyViewCount = 0;
    public void stopLoadingAnimation() {
        DLog.d("lLog", "activity stopLoadingAnimation()");
        if (isLoadingAnimationShow()) {
            mLoadingView.cancelAnimation();
            mLoadingView.setVisibility(View.GONE);
            showEmptyViewCount--;
            if (showEmptyViewCount == 0) {
                mEmptyView.setVisibility(View.GONE);
            }
        }
    }

    private boolean isLoadingAnimationShow() {
        return mLoadingView.getVisibility() == View.VISIBLE;
    }

    private String mBeforeGuideAction = ACTION_BACK;
    private static final String ACTION_BACK = "ACTION_BACK";
    private static final String ACTION_SHARE = "ACTION_SHARE";
    private static final String ACTION_TRY_AGAIN = "ACTION_TRY_AGAIN";

//    private RateGuide.OnRateChageListener mRateListener = new RateGuide.OnRateChageListener() {
//        @Override
//        public void onDisimiss() {
//            if (mBackFromGp) {
//                return;
//            }
//            if (TextUtils.equals(mBeforeGuideAction, ACTION_BACK)) {
//                onBack();
//            } else if (TextUtils.equals(mBeforeGuideAction, ACTION_SHARE)) {
//                showShareDialog(mShareImgPath);
//            } else {
//                //不展示弹窗
//                switch (mActionType) {
//                    case REPORT_TYPE_FACE_AGING:
//                        ((FaceAgingReportLogic) mReportLogic).checkAgeBtn(OneTimeVipHelper.getInstance().getAge());
//                        break;
////            case BaseFaceResultBean.REPORT_TYPE_EXOTIC:
////
////                break;
//                    case BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH:
//                        ((GenderSwitchReportLogic) mReportLogic).updateState();
//                        break;
//                    default:
//                        break;
//                }
//            }
//        }
//    };

    private boolean mBackFromGp = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFeedBackEvent(FeedBackEvent event) {
        mBackFromGp = true;
    }

//    private IRateDialogListener mListener = new IRateDialogListener() {
//        @Override
//        public void onScoreClick(int score) {
//            if (score >= 4) {
//                //好评
//                DialogStatistic.rateGoodComm(mWhere);
//            } else {
//                DialogStatistic.rateBadComm(mWhere);
//            }
//        }
//
//        @Override
//        public void onReasonSubmit(List<String> reasons) {
//
//        }
//
//        @Override
//        public void onCloseClick() {
//            DialogStatistic.rateClose(mWhere);
//        }
//    };

    @Override
    public void gotoHome() {
        mBeforeGuideAction = ACTION_BACK;
//
//        DialogShow.showRateGuideDialog(ENTRANCE_1, this, RateGuide.ACTION_USE_FUNC, mRateListener,
//                new IDialog.Listener() {
//                    @Override
//                    public void yes() {
//                        //展示了弹窗
//                        DialogStatistic.rateShow(mWhere);
//                    }
//
//                    @Override
//                    public void no() {
//                        //不展示弹窗
//                        StatisticsUtils.statisticsFaceSecret(STATISTIC_EVENT_REPORT_VALUE,
//                                StatisticsConstant.STATISTIC_EVENT_REPORT_VALUE_RETURN,
//                                StatisticsConstant.STATISTIC_EVENT_VALUE_CLICK_NEW,
//                                mReportLogic.getFeatureType(),
//                                FaceAgingReportLogic.isVersionBelowKitKat() ? StatisticsConstant.STATISTIC_VALUE_SYSTEM_BELOW_KITKAT : StatisticsConstant.STATISTIC_VALUE_SYSTEM_ABOVE_KITKAT);
//
//                        if (mActionType == REPORT_TYPE_FACE_AGING) {
//                            FaceAgingReportLogic.ISBACK_2_HOME = true;
//                        } /*else if (mActionType == REPORT_TYPE_BABYPREDICT) {
//                            BabyPredictReportLogic.ISBACK_2_HOME = true;
//                        }*/
//                        HomeActivity.back2Home(FaceLogicActivity.this);
//                    }
//                },
//                mListener);
        TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
            @Override
            public void run() {
                HomeActivity.back2Home(FaceLogicActivity.this);
            }
        };
        if (mMainReturnAdProvider != null) {
            mMainReturnAdProvider.showAd(taskRunnable);
        } else {
            taskRunnable.runSelfAdaptation();
        }
    }

    @Override
    public void switchImage() {
        enterGallery();
    }

    @Override
    public void updateResultBean() {
        if (mBaseFaceResultBean != null) {
            updateLogicResultBean();
        } else {
            process();
        }
    }

    @Override
    public void back() {
        onBack();
    }

    private void onBack() {
        gotoHome();
    }

    @Override
    protected void onDestroy() {
        ImmersionBar.with(this).destroy();

        super.onDestroy();
        mIsDestroy = true;
        EventBus.getDefault().unregister(this);

        if (mReportLogic instanceof FaceAgingReportLogic) {
            FaceAgingReportLogic timeMachineReportLogic = (FaceAgingReportLogic) mReportLogic;
            timeMachineReportLogic.destroy();
        }
        if (mReportLogic instanceof ExoticReportLogic) {
            ((ExoticReportLogic) mReportLogic).destroy();
        }
        if (mReportLogic instanceof GenderSwitchReportLogic) {
            ((GenderSwitchReportLogic) mReportLogic).destroy();
        }
        if (mReportLogic instanceof FutureBabyReportLogic) {
            ((FutureBabyReportLogic) mReportLogic).destroy();
        }

        long interval = System.currentTimeMillis() - timeCount;
        String stayTime;
        if (interval < 30 * 1000) {
            stayTime = "(0,30)";
        } else if (interval < 60 * 1000) {
            stayTime = "(30,60)";
        } else if (interval < 120 * 1000) {
            stayTime = "(60,120)";
        } else {
            stayTime = "(120,)";
        }
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_SHOW,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_STAY_TIME, stayTime);

        if (mMainReturnAdProvider != null) {
            mMainReturnAdProvider.destroyAd();
        }
    }

    @Override
    public void onBackPressed() {
        if (isLoadingAnimationShow()) {
            stopLoadingAnimation();
            ToastUtil.showToast("Cancel face checked");
            return;
        }
        if (mReportLogic instanceof FaceAgingReportLogic) {
            FaceAgingReportLogic timeMachineReportLogic = (FaceAgingReportLogic) mReportLogic;
            if (timeMachineReportLogic.isLoading()) {
                timeMachineReportLogic.onBackPressed();
            } else {
                onBack();
            }
        } else {
            onBack();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_save:
                if (AppVipManager.isVip() || isModel) {
                    checkPermission();
                } else {
                    switch (mActionType) {
                        case REPORT_TYPE_FACE_AGING:
                            int location = ((FaceAgingReportLogic) mReportLogic).getLocation();
                            if (location == 0) {
                                int age = ((FaceAgingReportLogic) mReportLogic).getCurrentAge();
                                if (OneTimeVipHelper.getInstance().isAgeUnlocked(age)) {
                                    checkPermission();
                                } else {
                                    showSubscribeDialog(false);
                                }
                            } else {
                                String templateId = ((FaceAgingReportLogic) mReportLogic).getCurrentTemplateId();
                                if (OneTimeVipHelper.getInstance().isTemplateUnlocked(templateId)) {
                                    checkPermission();
                                } else {
                                    showSubscribeDialog(false);
                                }
                            }
//                            if (OneTimeVipHelper.getInstance().isAgeUnlocked() ||
//                                    OneTimeVipHelper.getInstance().isTemplateUnlocked()) {
//                                checkPermission();
//                            } else {
//                                showSubscribeDialog(false);
//                            }
                            break;
                        case REPORT_TYPE_EXOTIC:
                            if (OneTimeVipHelper.getInstance().isTemplateUnlocked()) {
                                checkPermission();
                            } else {
                                showSubscribeDialog(false);
                            }
                            break;
                        case REPORT_TYPE_GENDER_SWITCH:
                            location = ((GenderSwitchReportLogic)mReportLogic).getLocation();
                            if (location == 0) {
                                if (OneTimeVipHelper.getInstance().isGenderSwitchUnlocked()) {
                                    checkPermission();
                                } else {
                                    showSubscribeDialog(false);
                                }
                            } else {
                                String templateId = ((GenderSwitchReportLogic)mReportLogic).getCurrentTemplateId();
                                if (OneTimeVipHelper.getInstance().isTemplateUnlocked(templateId)) {
                                    checkPermission();
                                } else {
                                    showSubscribeDialog(false);
                                }
                            }

//                            if (OneTimeVipHelper.getInstance().isGenderSwitchUnlocked() ||
//                                    OneTimeVipHelper.getInstance().isTemplateUnlocked()) {
//                                checkPermission();
//                            } else {
//                                showSubscribeDialog(false);
//                            }
                            break;
                        case REPORT_TYPE_PAST_LIFE:
                            if (AppVipManager.isVip()) {
                                checkPermission();
                            } else {
                                showSubscribeDialog(false);
                            }
                            break;
                    }
                }
        }
    }

    private void onSave2() {
        getSaveTask().execute(mImgSavePath, System.currentTimeMillis() + ".jpg");

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_SAVE, StatisticsConstant.KEY_TREND_FUN,
                mReportLogic.getFeatureType());

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_SAVE, StatisticsConstant.KEY_TREND_FUN,
                mReportLogic.getFeatureType());
    }

    private AsyncTask<String, Integer, Boolean> getSaveTask() {
        AsyncTask<String, Integer, Boolean> mSaveImageTask = new AsyncTask<String, Integer, Boolean>() {

            @Override
            protected Boolean doInBackground(String... params) {
                if (params != null && params.length == 2) {
                    Bitmap bitmap;
                    {
                        bitmap = mReportLogic.getSaveImg();
                    }
                    int quality = 100;

                    boolean success;
                    success = ImageHelper.saveBitmapAsJPG(FaceLogicActivity.this, bitmap, quality, params[0], params[1], new FolderHelper.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, final Uri uri, int orientation) {
                            dealUriBrocast(uri, path);
                        }
                    });
                    return success;
                }
                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
//                getLoadingView().stopLoading();
                StatisticsUtils.statisticsEditResult(result);
                if (result) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_save_success), Toast.LENGTH_SHORT).show();
                    // 编辑成功，保持编辑次数
                    SPDataManager.setEditCount(SPDataManager.getEditCount() + 1);
                } else {//失败了直接Dismiss掉
//                    if (mSaveTaskProgressDialog != null && !isFinishing()) {
//                        mSaveTaskProgressDialog.dismiss();
//                    }
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_save_fail), Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        };

        return mSaveImageTask;
    }

    private void dealUriBrocast(final Uri u, final String path) {
        TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
            @Override
            public void run() {

                try {
//                    mSaveTaskProgressDialog.dismiss();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                SpUtils.obtain().save(SpConstant.IS_NEED_TO_SAVE, !isModel);
                ImagePreviewActivity.startPictureViewActivityAndStartShare(FaceLogicActivity.this, u, null, getEntranceName(), mWhere, degree);
                degree = 0;
                int saveCount = SpUtils.obtain().getInt("edit_save", 0);
                if (saveCount < 2) {
                    SpUtils.obtain().save("edit_save", saveCount + 1);
                }
                finish();
            }
        };
        onSave(taskRunnable);
    }

    private void onSave(TaskRunnable taskRunnable) {
        if (taskRunnable != null) {
            taskRunnable.runSelfAdaptation();
        }
    }

    private void onSave() {
        boolean saveResult = false;
        String path = "";
        File savePath = null;
        try {
            File saveDir = new File(mImgSavePath);
            if (!saveDir.exists() || !saveDir.isDirectory()) {
                saveDir.mkdir();
            }
            path = mImgSavePath + File.separator + System.currentTimeMillis() + ".jpg";
            savePath = new File(path);
            savePath.createNewFile();
            Bitmap shareImg;
            {
                shareImg = mReportLogic.getSaveImg();
            }
            if (shareImg != null && !shareImg.isRecycled()) {
                saveResult = ImageHelper.saveBitmapToSdcardForShare(path, shareImg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (saveResult && savePath != null) {
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, ComponentContext.getPackageName() + ".fileprovider", new File(path));
            } else {
                uri = Uri.fromFile(new File(path));
            }
            try {
                MediaStore.Images.Media.insertImage(getContentResolver(), savePath.getAbsolutePath(), savePath.getName(), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//            showShareDialog(path);
//            ToastUtil.showToast(ComponentContext.getContext(), R.string.save_img_success);
            ImagePreviewActivity.startPictureViewActivityAndStartShare(ComponentContext.getContext(), uri, null, "edit", mWhere, degree);
        } else {
            ToastUtil.showToast(ComponentContext.getContext(), R.string.save_img_fail);
        }

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_SAVE, StatisticsConstant.KEY_TREND_FUN,
                mReportLogic.getFeatureType());
    }

//    String mShareImgPath;

//    private void showShareDialog(final String imgPath) {
//        mBeforeGuideAction = ACTION_SHARE;
//
//        DialogShow.showRateGuideDialog(ENTRANCE_1, this, RateGuide.ACTION_USE_FUNC, mRateListener,
//                new IDialog.Listener() {
//                    @Override
//                    public void yes() {
//                        //展示了弹窗
//                        mShareImgPath = imgPath;
//                        DialogStatistic.rateShow(mWhere);
//                    }
//
//                    @Override
//                    public void no() {
//                        //不展示弹窗
//                        if (mShareImageDialogHelp == null) {
//                            mShareImageDialogHelp = new ShareImageDialogHelp(FaceLogicActivity.this);
//                        }
//                        BitmapBean bean = new BitmapBean();
//                        bean.mPath = imgPath;
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            bean.mUri = FileProvider.getUriForFile(FaceLogicActivity.this, ComponentContext.getPackageName() + ".fileprovider", new File(imgPath));
//                        } else {
//                            bean.mUri = Uri.fromFile(new File(imgPath));
//                        }
//                        mShareImageDialogHelp.showShareDialogBottom(bean);
//                    }
//                },
//                mListener);
//    }

    @Override
    protected void onResume() {
        super.onResume();
        statisticsResultShow();
//        if (mReportLogic instanceof GenderSwitchReportLogic) {
//            mReportLogic.updateMaskLayout();
//        } else if (mReportLogic instanceof FutureBabyReportLogic) {
//            mReportLogic.updateMaskLayout();
//        }
//        checkVipView(false);
        initStatistics();

        if (mDrawable != null) {
            mDrawable.start();
        }

        if (mBackFromGp) {
            mBackFromGp = false;
//            if (mRateListener != null) {
//                mRateListener.onDisimiss();
//            }
        }

        if (mReachGP) {
            mReachGP = false;
            EventBus.getDefault().post(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_ONE_DAY));
        }
    }

    private void initStatistics() {
//        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_SHOW, StatisticsConstant.KEY_TREND_FUN,
//                mReportLogic.getFeatureType());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubscribeSuccessEvent(SubscribeSuccessEvent event) {
        switch (event.subType) {
            case SubscribeSuccessEvent.SUB_TYPE_BUY:
                //真实购买后获得vip

                break;
            case SubscribeSuccessEvent.SUB_TYPE_ONE_DAY:
                //五星好评后获得一天vip
                SPDataManager.setOneDayVipTime();
                break;
            case SubscribeSuccessEvent.SUB_TYPE_ONE_TIME:
                //观看激励视频后获得一次使用机会
                switch (mActionType) {
                    case REPORT_TYPE_FACE_AGING:
                        int location = ((FaceAgingReportLogic) mReportLogic).getLocation();
                        if (location == 0) {
                            OneTimeVipHelper.getInstance().unlockAge();
                            DLog.d("lLog", "face aging location 0");
                            if (OneTimeVipHelper.getInstance().getUnlockedAgeCount() > 0) {
                                //第二次及后面不用重新扫描
                                ((FaceAgingReportLogic) mReportLogic).checkAgeBtn(OneTimeVipHelper.getInstance().getLatestUnlockedAge());
                                return;
                            }
                        } else {
                            DLog.d("lLog", "face aging location 1");
                            OneTimeVipHelper.getInstance().unlockTemplateId();
                            if (OneTimeVipHelper.getInstance().getUnlockedTemplateCount() > 0){
                                ((FaceAgingReportLogic) mReportLogic).checkTemplateBtn(OneTimeVipHelper.getInstance().getLatestUnlockedTid());
                            }
                        }
                        break;
//                    case BaseFaceResultBean.REPORT_TYPE_EXOTIC:
//                        OneTimeVipHelper.getInstance().unlockTemplateId();
//                        if (OneTimeVipHelper.getInstance().getUnlockedTemplateCount() > 1) {
//                            //同上
//                            ((ExoticReportLogic)mReportLogic).mergeTemplate(OneTimeVipHelper.getInstance().getLatestUnlockedTid());
//                            return;
//                        }
//                        break;
                    case BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH:
                        location = ((GenderSwitchReportLogic)mReportLogic).getLocation();
                        if (location == 0) {
//                            SPDataManager.setAdOneTimeVip(true);
                            DLog.d("lLog", "gender switch location 0");
                            OneTimeVipHelper.getInstance().unlockGenderSwitch();
                        } else {
                            DLog.d("lLog", "gender switch location 1");
                            OneTimeVipHelper.getInstance().unlockTemplateId();
                            if (OneTimeVipHelper.getInstance().getUnlockedTemplateCount() > 0){
                                ((GenderSwitchReportLogic) mReportLogic).doRequest(OneTimeVipHelper.getInstance().getLatestUnlockedTid());
                            }
                        }
                        break;
                    case REPORT_TYPE_BABYPREDICT:
                        SPDataManager.setAdOneTimeVip(true);
                        break;
                    case BaseFaceResultBean.REPORT_TYPE_PAST_LIFE:
                        SPDataManager.setAdOneTimeVip(true);
                        break;
                    default:
                        break;
                }
                break;
        }
        mReportLogic.onSubscribeSuccess();
    }

    private void statisticsClose() {

        String entranceName = getEntranceName();
        if (TextUtils.isEmpty(entranceName)) {
            return;
        }
        VipStatisticUtil.statistic(STATISTIC_EVENT_VIP_PAGE_RESULTPAGE,
                entranceName,
                STATISTIC_EVENT_FUN_VALUE_CLOSE);

    }

    private void statisticsResultShow() {
        String entranceName = getEntranceName();
        if (TextUtils.isEmpty(entranceName)) {
            return;
        }

        if (!isVipByType()) {
            // 模糊页重新显示
            VipStatisticUtil.statistic(STATISTIC_EVENT_VIP_PAGE_RESULTPAGE,
                    entranceName,
                    STATISTIC_EVENT_FUN_VALUE_SHOW);
        }


    }

    private void statisticsClickGet() {
        String entranceName = getEntranceName();
        if (TextUtils.isEmpty(entranceName)) {
            return;
        }

        // 商业化
        VipStatisticUtil.statistic(STATISTIC_EVENT_VIP_PAGE_RESULTPAGE,
                entranceName,
                STATISTIC_EVENT_FUN_VALUE_CLICK);

    }

    private String getEntranceName() {
        String entranceName;
        if (mActionType == REPORT_TYPE_FACE_AGING) {
            entranceName = StatisticsConstant.STATISTIC_EVENT_VIP_ENTRANCE_GETOLD;
        } else if (mActionType == BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH) {
            entranceName = StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH;
        } else {
            return null;
        }
        return entranceName;
    }

    private boolean isVipByType() {
        boolean isVip = false;
        if (mBaseFaceResultBean != null) {
            switch (mActionType) {
                case REPORT_TYPE_FACE_AGING:
                    isVip = AppVipManager.isFaceAgingVip();
                    break;
                default:
                    break;
            }
        }
        return isVip;
    }

    private boolean mIsFirst = true;
    private @DialogStatistic.AdVideoWhere int adVideoWhere;

    //老化，换性，前世今生，宝宝功能调用这个跳转功能订阅页
    public void showSubscribeDialog(final boolean first) {
        if (!SPDataManager.whetherShowedAdVideoDialogInAdvanceResultPage()) {
            SVipController.showFunctionSubscribe(this,mActionType,StatisticsConstant.ENTRANCE_VALUE_FACE_AGING,
                    new SVipController.OnSubscribeCloseListener() {
                        @Override
                        public void onSubscribeClose() {
                            adVideoWhere= DialogStatistic.AdVideoWhere.VALUE_WHERE_GENDER_SWAP;
                            switch (mActionType) {
                                case REPORT_TYPE_FACE_AGING:
                                    adVideoWhere = DialogStatistic.AdVideoWhere.VALUE_WHERE_FACE_AGING;
                                    break;
                                case REPORT_TYPE_EXOTIC:
                                    adVideoWhere = DialogStatistic.AdVideoWhere.VALUE_WHERE_FACE_SWAP;
                                    break;
                                case REPORT_TYPE_GENDER_SWITCH:
                                    adVideoWhere = DialogStatistic.AdVideoWhere.VALUE_WHERE_GENDER_SWAP;
                                    break;
                                case REPORT_TYPE_PAST_LIFE:
                                    adVideoWhere = DialogStatistic.AdVideoWhere.VALUE_WHERE_PAST_LIFE;
                                    break;
                                case REPORT_TYPE_BABYPREDICT:
                                    adVideoWhere = DialogStatistic.AdVideoWhere.VALUE_WHERE_FUTURE_BABY;
                                    break;

                                default:
                                    adVideoWhere = 0;
                                    break;
                            }
                            mReportLogic.updateMaskLayout();

                            if ((SPDataManager.getTodayHasShowedAllSubscribeMaskCount() ==1 )) {
                                //每天第一次关闭功能订阅页展示激励视频弹窗
                                showWDialog();
                            }
                            //关闭订阅页，执行评分引导一天免费弹框或者广告视频弹框
//                            WDialogShow.showLuckyUserOrInspireAdVideoDialog(FaceLogicActivity.this,
//                                    DialogShow.InspireDialogEntrance.ENTRANCE_1, mStatisticRetain, adVideoWhere,dialogListener);
                        }
                    });
        } else {
            SVipController.showFunctionSubscribe(this, mActionType,StatisticsConstant.ENTRANCE_VALUE_FACE_AGING, null);
        }
    }

    //直接显示激励视频弹窗
    public void showWDialog(){
        DialogShow.showAdVideoDialog(DialogShow.InspireDialogEntrance.ENTRANCE_1, FaceLogicActivity.this, mStatisticRetain, adVideoWhere, new IDialog.Listener() {
            @Override
            public void yes() {
                //弹窗展示后,计入统计
                SPDataManager.setIsShowAdvanceDialog(false);
                if (adVideoWhere != DialogStatistic.AdVideoWhere.VALUE_WHERE_TOOL) {
                    SPDataManager.hasShowedAdVideoDialogInAdvanceResultPage();
                }
                if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_FACE_AGING){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                            StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING);
                }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_GENDER_SWAP) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_SWAP,
                            StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_VIP_FUN_FACE_SWAP);
                }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_PAST_LIFE){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE,
                            StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
                }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_MATERIAL){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                            StatisticsConstant.KEY_FILTER_NAME, SpUtils.obtain().getString(EFFECT_NAME, ""));
                }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_TOOL){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_TOOL,
                            StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_TOOL);
                }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_FUTURE_BABY){
                    SpUtils.obtain().save(EFFECT_NAME, "baby");
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY,
                            StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY);
                }
            }
        }, dialogListener);
    }

    IAdVideoDialogListener dialogListener=new IAdVideoDialogListener() {
        @Override
        public void onSureClick() {
            if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_FACE_AGING){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_FACE_AGING);
                SpUtils.obtain().save(EFFECT_NAME, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING);
            }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_GENDER_SWAP){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP);
                SpUtils.obtain().save(EFFECT_NAME, StatisticsConstant.VALUE_VIP_FUN_GENDER_SWAP);
            }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_PAST_LIFE){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
                SpUtils.obtain().save(EFFECT_NAME, StatisticsConstant.VALUE_VIP_FUN_PAST_LIFE);
            }else if(adVideoWhere==DialogStatistic.AdVideoWhere.VALUE_WHERE_FUTURE_BABY){
                SpUtils.obtain().save(EFFECT_NAME, "baby");
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY);
            }
            DialogStatistic.adVideoSureClick(mWhere);
        }

        @Override
        public void onCancelClick() {
            DialogStatistic.adVideoCancelClick(mWhere);
        }


        @Override
        public void onCloseClick() {
            DialogStatistic.adVideoClose(mWhere);
        }
    };

    private boolean mReachGP = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReachGP(ReachGPEvent event) {
        mReachGP = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotoSubscribePageEvent(GotoSubscribePageEvent event) {
        showSubscribeDialog(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotoAdVideoPageEvent(GotoAdVideoPageEvent event) {
        //isfromButton =true;
        SpUtils.obtain().save(ISFROMBUTTON, true);
        mRewardAdManager.showRewardAdVideo();
    }

    public static boolean getIsFromButton(){
        return isfromButton;
    }

    public static void setIsFromButton(boolean isfromButton){
        isfromButton=isfromButton;
    }

    public int getType() {
        return mReportLogic.getReportType();
    }

    private long mLastLeaveTime;

    @Override
    protected void onStop() {
        super.onStop();
        if (!isVipByType() && AppFrontBackHelper.getInstant().isAppBackground()) {
            long time = System.currentTimeMillis();
            if (time - mLastLeaveTime <= 300) {
                return;
            }
            mLastLeaveTime = time;
            //    if (mSubscribePageId == SVipConstant.VIP_RETAIN_B) {
            StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                    , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                    , mStatisticRetain
                            + StatisticsConstant.STATISTIC_UNDERLINE
                            + StatisticsConstant.STATISTIC_EVENT_VALUE_LEAVE
                            + VipStatisticUtil.getKeySuffix());
            //            } else {
            //                if (mASubscribeView != null) {
            //                    mASubscribeView.onStop();
            //                }
            //            }

//            String stayTime;
//            if (time - mLastLeaveTime < 30 * 1000) {
//                stayTime = "(0,30)";
//            } else if (time - mLastLeaveTime < 60 * 1000) {
//                stayTime = "(30,60)";
//            } else if (time - mLastLeaveTime < 120 * 1000) {
//                stayTime = "(60,120)";
//            } else {
//                stayTime = "(120,)";
//            }
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_SHOW, "stayTime",
//                    stayTime);
        }

        if (mDrawable != null) {
            mDrawable.stop();
        }
    }

    public void checkPermission() {
        if (PermissionChecker.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            AndPermission.with(this)
                    .requestCode(202)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(listener)
                    .start();
        } else {
            onSave2();
//            onSave();
        }
    }

    //权限监听回调
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 202) {
                onSave2();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            ToastUtil.showToast(getString(R.string.failed_to_save));
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOldSuccessEvent(AgeSuccessEvent event) {
        updateBlurImg();
    }

    private void updateBlurImg() {
        mScreenView.setDrawingCacheEnabled(true);
        mScreenView.buildDrawingCache();
        Bitmap ret = Bitmap.createBitmap(mScreenView.getDrawingCache());
        mScreenView.destroyDrawingCache();
        mScreenView.setDrawingCacheEnabled(false);
        Bitmap blur = BlurUtil.blur(ComponentContext.getContext(), ret, 25);
        // 裁剪图片
        RectF rect = new RectF(0, DeviceUtils.dip2px(120) + 315, DeviceUtils.getScreenWidthPx(), DeviceUtils.getScreenHeightPx());
        Bitmap bitmap = BitmapUtils.getRectBitmap(rect, blur, DisplayUtils.getScreenMetrics(ComponentContext.getContext()));

    }

    public Bitmap getSaveImg() {
        Bitmap ret = null;
        if (mRenderParent != null) {
            mRenderParent.setDrawingCacheEnabled(true);
            mRenderParent.buildDrawingCache();
            Bitmap cache = mRenderParent.getDrawingCache();
            ret = cache;
            if (cache == null) {
                Bitmap bitmap = Bitmap.createBitmap(mRenderParent.getWidth(),
                        mRenderParent.getHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                mRenderParent.draw(canvas);
                ret = bitmap;
            }
        }
        return ret;
    }

    private String getStatisType(int funId) {
        String type = StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_AGING;
        switch (funId) {
            case REPORT_TYPE_FACE_AGING:
                type = StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_AGING;
                break;
            case BaseFaceResultBean.REPORT_TYPE_EXOTIC:
                type = StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP;
                break;
            case BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH:
                type = StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH;
                break;
            default:
                break;
        }
        return type;
    }

    public View getEmptyView() {
        return mEmptyView;
    }

    private void updateLogicResultBean() {
        switch (mAction) {
            case ACTION_FACE_AGING:
                ((FaceAgingReportLogic) mReportLogic).setResultBean((FaceAgingResultBean) mBaseFaceResultBean);
                break;
            case ACTION_GENDER_SWITCH:
                ((GenderSwitchReportLogic) mReportLogic).setResultBean((FaceDetectBeanV4) mBaseFaceResultBean);
                break;
            case ACTION_PAST_LIFE:
                ((PastLifeReportLogic) mReportLogic).setResultBean((FaceDetectBeanV4) mBaseFaceResultBean);
                break;
            case ACTION_FUTURE_BABY:
                ((FutureBabyReportLogic) mReportLogic).setResultBean((FaceDetectBeanV4) mBaseFaceResultBean);
                break;
        }
    }

    /**
     * 检测照片逻辑
     */
    private FaceBaseCallback mDetectFaceCallback = new FaceBaseCallback() {

        private void doNext(List beans) {
            switch (mAction) {

                case ACTION_FACE_AGING:
                    FaceAgingFaceBean faceDetectBean = (FaceAgingFaceBean) beans.get(0);
                    mBaseFaceResultBean = FaceUtil.parseFaceAgingFaceDetectBean2ResultBean(faceDetectBean, null);
                    break;
                case ACTION_EXOTIC_BLEND:
                    mBaseFaceResultBean = (FaceDetectBeanV4) beans.get(0);

                    break;
                case ACTION_GENDER_SWITCH:
                    mBaseFaceResultBean = (FaceDetectBeanV4) beans.get(0);
                    mBaseFaceResultBean.setType(BaseFaceResultBean.REPORT_TYPE_GENDER_SWITCH);
                    break;
                case ACTION_PAST_LIFE:
                    mBaseFaceResultBean = (FaceDetectBeanV4) beans.get(0);
                    mBaseFaceResultBean.setType(BaseFaceResultBean.REPORT_TYPE_PAST_LIFE);
                    break;
                case ACTION_FUTURE_BABY:
                    mBaseFaceResultBean = (FaceDetectBeanV4) beans.get(0);
                    mBaseFaceResultBean.setType(BaseFaceResultBean.REPORT_TYPE_BABYPREDICT);
                    break;
                default:
                    break;
            }
            //若没有正在加载，表示用户已取消，先不更新，待用户点击后更新
            if (isLoadingAnimationShow()) {
                updateLogicResultBean();
            }
        }

        @Override
        public void onSuccess(Response response) {
            if (mIsDestroy) {
                return;
            }
            try {
                okhttp3.Response rawResponse = response.getRawResponse();
                String result = rawResponse.body().string();
                DLog.d(TAG, "detect face response: \n" + result);
                List beans = new ArrayList();
                int retType = FaceUtil.parseResult(result, getDetectFaceType(mAction), beans);
                mScanResultType = retType;
                if (retType != RESULT_SUCCESS) {
                    ToastUtil.showToast("Please select a photo with one complete human face");
                    if (DebugUtil.isDebuggable())
                        ToastUtil.showToast(getErrorTypeByReturnType(retType));
                    statisticRequestError(getErrorTypeByReturnType(retType));
                    stopLoadingAnimation();
                    return;
                }
                statisticRequestSuccess();
                doNext(beans);
                mGetResponse = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!TextUtils.equals(mAction, ACTION_FACE_AGING)) {
                stopLoadingAnimation();
            }
        }

        @Override
        public void onError(Response response) {
            if (mIsDestroy) {
                return;
            }

            mGetResponse = false;
            ToastUtil.showToast("Network unavailable. Please try again later");
            if (DebugUtil.isDebuggable()) ToastUtil.showToast("response error");
            statisticRequestError(STATISTIC_EVENT_FUN_VALUE_OTHER_ONLINE_ERROR);
            mScanResultType = RESULT_OTHER;
            try {
                String result = response.getException().getMessage();
                DLog.d(TAG, "response erro: " + result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            stopLoadingAnimation();
        }

        @Override
        public void onStart(Request request) {
            super.onStart(request);
            mGetResponse = false;
        }
    };

    private void statisticRequestError(String errorType) {
        statisticRequestError(errorType, false);
    }

    private void statisticRequestError(String errorType, boolean fromCreate) {
        if (!NetworkUtils.isNetworkAvailable(this) && !fromCreate) {
            errorType = StatisticsConstant.REQUEST_PAGE_VALUE_REASON_NETWORK;
        }

//        if (mAction.equals(ACTION_FACE_AGING)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_FAILED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING, StatisticsConstant.KEY_REQUEST_FAILED_REASON, errorType);
//        } if (mAction.equals(ACTION_EXOTIC_BLEND)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_FAILED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP, StatisticsConstant.KEY_REQUEST_FAILED_REASON, errorType);
//        } else if (mAction.equals(ACTION_GENDER_SWITCH)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_FAILED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH, StatisticsConstant.KEY_REQUEST_FAILED_REASON, errorType);
//        }

//        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_FAIL,
//                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
//                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
//                StatisticsConstant.KEY_PIC_SOURCE, picSource,
//                StatisticsConstant.KEY_REQUEST_FAILED_REASON, errorType);
        statisticDetectFaceSFail(errorType);
    }

    private void statisticRequestSuccess() {
//        String type = "";//getFaceScanParkingTimeType();
//        if (mAction.equals(ACTION_FACE_AGING)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_SUCCEED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING, StatisticsConstant.KEY_REQUEST_TIME, type);
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_SUCCEED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING, StatisticsConstant.KEY_REQUEST_TIME, type);
//        } else if (mAction.equals(ACTION_EXOTIC_BLEND)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_SUCCEED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP, StatisticsConstant.KEY_REQUEST_TIME, type);
//        } else if (mAction.equals(ACTION_GENDER_SWITCH)) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST_SUCCEED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH, StatisticsConstant.KEY_REQUEST_TIME, type);
//        }
        statisticDetectFaceSuccess();
//        }
    }

    private AsyncTask<Void, Void, Boolean> getDetectSingleImgTask() {
        return new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Boolean doInBackground(Void... params) {
                int detectFaceType = getDetectFaceType(mAction);
                if (mImgYou == null || mImgYou.isRecycled()) return false;
                String optimizedImgBase64 = getOptimizeBmpBase64(mImgYou);
                if (optimizedImgBase64 == null || optimizedImgBase64.equals("")) return false;
                detectFace(detectFaceType, optimizedImgBase64);
                return true;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                if (!aBoolean.booleanValue()) {
                    ToastUtil.showToast("Network unavailable. Please try again later");
                    if (DebugUtil.isDebuggable())
                        ToastUtil.showToast(getErrorTypeByReturnType(RESULT_PARSE_IMG_ERROR));
                    mScanResultType = RESULT_PARSE_IMG_ERROR;

                    statisticRequestError(STATISTIC_EVENT_FUN_VALUE_OTHER_CLINET);
                    stopLoadingAnimation();
                }
            }
        };
    }

    private void detectFace(int type, String imgBase64) {
        switch (mAction) {
            case ACTION_FACE_AGING:
//                mDetectFaceCallback.setIsDetectTwoImg(false);
//                FaceUtil.detectFace(imgBase64, FaceReportActivity.this, mDetectFaceCallback, type);
//                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST, StatisticsConstant.KEY_TREND_FUN,
//                        StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING);

                mImageFaceDetector = new ImageFaceDetector();
                mImageFaceDetector.setListener(this);
                mReportViewContainer.post(new DetectFaceTask());

                mDetectFaceCallback.setIsDetectTwoImg(false);
                FaceUtil.detectFace(imgBase64, FaceLogicActivity.this, mDetectFaceCallback);
                break;

            case ACTION_EXOTIC_BLEND:
                mDetectFaceCallback.setIsDetectTwoImg(false);
                FaceUtil.detectFace(imgBase64, FaceLogicActivity.this, mDetectFaceCallback);
//                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST, StatisticsConstant.KEY_TREND_FUN,
//                        StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP);
                break;

            case ACTION_GENDER_SWITCH:
                mDetectFaceCallback.setIsDetectTwoImg(false);
                FaceUtil.detectFace(imgBase64, FaceLogicActivity.this, mDetectFaceCallback);
//                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCANNING_PAGE_REQUEST, StatisticsConstant.KEY_TREND_FUN,
//                        StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH);
                break;

            case ACTION_PAST_LIFE:
                mDetectFaceCallback.setIsDetectTwoImg(false);
                FaceUtil.detectFace(imgBase64, FaceLogicActivity.this, mDetectFaceCallback);
                break;
            default:
                break;
        }

//        switch (getIntent().getIntExtra(FaceConstant.EXTRA_FROM, 0)) {
//            case 0:
//                picSource = "model";
//                break;
//            case 1:
//                picSource = "album";
//                break;
//            case 2:
//                picSource = "camera";
//                break;
//        }
        timeCount = System.currentTimeMillis();
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource);
    }

    @Override
    public void onDetectFaceSuccess(@NonNull List<FirebaseVisionFace> results) {
        DLog.d("wLog", "success1");
    }

    @Override
    public void onDetectFaceFailure(@NonNull Exception e) {
        DLog.d("wLog", "fail1");
    }

    @Override
    public void onDetectFaceLandmarkSuccess(@NonNull List<FirebaseVisionFace> results) {
        DLog.d("wLog", "success");
        if (!TextUtils.equals(mAction, ACTION_FACE_AGING)) {
            stopLoadingAnimation();
        }
        dealDetectFaceLandmarkSuccess(results);
    }

    @Override
    public void onDetectFaceLandmarkFailure(@NonNull Exception e) {
        DLog.d("wLog", "fail");
        if (!TextUtils.equals(mAction, ACTION_FACE_AGING)) {
            stopLoadingAnimation();
        }
    }

    class DetectFaceTask implements Runnable {
        @Override
        public void run() {
            Bitmap bmpOnScreen = ((FaceAgingReportLogic) mReportLogic).getBitmapOnScreen();
            if (bmpOnScreen == null || bmpOnScreen.isRecycled()) {
                ToastUtil.showToast(ComponentContext.getContext(), R.string.detect_face_error);
                statisticDetectFaceSFail("noface");
                return;
            }
            RelativeLayout.LayoutParams modelLp = (RelativeLayout.LayoutParams) mModelView.getLayoutParams();
            modelLp.width = bmpOnScreen.getWidth() - DeviceUtils.dip2px(11);
            modelLp.height = bmpOnScreen.getHeight() - DeviceUtils.dip2px(11);
            modelLp.setMarginStart(DeviceUtils.dip2px(27));
            modelLp.setMarginEnd(DeviceUtils.dip2px(27));
            View modelMaskView = findViewById(R.id.model_mask_view);
            RelativeLayout.LayoutParams medelMaskLp = (RelativeLayout.LayoutParams) modelMaskView.getLayoutParams();
            medelMaskLp.width = modelLp.width;
            medelMaskLp.height = modelLp.height;
            medelMaskLp.setMarginStart(modelLp.getMarginStart());
            medelMaskLp.setMarginEnd(modelLp.getMarginEnd());
            ViewGroup.LayoutParams gpuImageLp = mGPUImageView.getLayoutParams();
            gpuImageLp.width = bmpOnScreen.getWidth() - DeviceUtils.dip2px(11);
            gpuImageLp.height = bmpOnScreen.getHeight() - DeviceUtils.dip2px(11);
            ViewGroup.LayoutParams decLayoutParams = mDecorationView.getLayoutParams();
            decLayoutParams.width = bmpOnScreen.getWidth() - DeviceUtils.dip2px(11);
            decLayoutParams.height = bmpOnScreen.getHeight() - DeviceUtils.dip2px(11);
            mImageFaceDetector.startDetectLandmark(bmpOnScreen);
        }
    }

    private void dealDetectFaceLandmarkSuccess(@NonNull List<FirebaseVisionFace> results) {
        if (results == null || results.size() == 0) {
            Toast.makeText(FaceLogicActivity.this, getString(R.string.detect_face_error), Toast.LENGTH_SHORT).show();
            ((FaceAgingReportLogic) mReportLogic).check50ForSub();
            statisticDetectFaceSFail("noface");
            return;
        }
        if (results.size() >= 2) {
            Toast.makeText(FaceLogicActivity.this, getString(R.string.detect_face_error), Toast.LENGTH_SHORT).show();
            statisticDetectFaceSFail("other");
            return;
        }
        CommonFaceBean bean = FaceUtil.parseCommonFaceBean(results.get(0), 1f, 1f);//no scale
        ((FaceAgingReportLogic) mReportLogic).setDetectFaceResult(bean);
        ((FaceAgingReportLogic) mReportLogic).bindView(mModelView, (My3DRenderer) mRender, mGPUImageView, mDecorationView);
        ((FaceAgingReportLogic) mReportLogic).check50ForSub();
        statisticDetectFaceSuccess();
    }

    private void statisticDetectFaceSuccess() {
        long interval = System.currentTimeMillis() - timeCount;
        String requTime = "";
        if (interval < 4 * 1000) {
            requTime = "(0,4)";
        } else if (interval < 6 * 1000) {
            requTime = "(4,6)";
        } else if (interval < 10 * 1000) {
            requTime = "(6,10)";
        } else {
            requTime = "(10,)";
        }
//        if (mAction.equals(ACTION_FACE_AGING)){
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_SUCCESS,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource,
                StatisticsConstant.KEY_REQ_TIME, requTime);
    }

    private void statisticDetectFaceSFail(String errorType) {
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_FAIL,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource,
                StatisticsConstant.KEY_REQUEST_FAILED_REASON, errorType);
    }

    /**
     * 换照片逻辑
     */
    public void enterGallery() {
        String entrance = "";
        boolean startNew = false;
        switch (mAction) {
            case ACTION_FACE_AGING:
                entrance = "face_logic_aging";
                StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_ALBUMCLICK, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_AGING);
                break;
            case ACTION_EXOTIC_BLEND:
                entrance = "";
                break;
            case ACTION_GENDER_SWITCH:
                entrance = "face_logic_logic_gender";
                StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_ALBUMCLICK, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_GENDER);
                break;
            case ACTION_PAST_LIFE:
                entrance = "face_logic_past_life";
                StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_ALBUMCLICK, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_PAST);
                break;
            case ACTION_FUTURE_BABY:
                entrance = "face_logic_baby_predict";
                StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_ALBUMCLICK, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_BABY);
                startNew = true;
                break;
        }
        if (startNew) {
            BabyMainActivity.startActivity(this);
            finish();
        } else {
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, this, GalleryActivity.class);
            intent.setType("image/*");
            intent.putExtra(GalleryActivity.EXTRA_ENTRANCE, entrance);
            intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, "face");
            startActivityForResult(intent, REQUEST_CODE_CHOOSE_PHOTO_YOU);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&
                requestCode == REQUEST_CODE_CHOOSE_PHOTO_YOU) {
            DLog.d("vipLog", "setAdOneTimeVip false");
            SPDataManager.setAdOneTimeVip(false);
            Uri imageUri = data.getData();
            preApplyImg(imageUri, data.getStringExtra(EXTRA_KEY_IMAGE_YOUS));

            int from = data.getIntExtra(FaceConstant.EXTRA_FROM, 0);
            switch (from) {
                default:
                case 0:
                    picSource = "model";
                    break;
                case 1:
                    picSource = "album";
                    if (!AppVipManager.isVip()) {
                        showSubscribeDialog(true);
                    }
                    break;
                case 2:
                    picSource = "camera";
                    if (!AppVipManager.isVip()) {
                        showSubscribeDialog(true);
                    }
                    break;
            }
        } else if (requestCode == 99) {
            if (mReportLogic instanceof FaceAgingReportLogic) {
                mReportLogic.updateMaskLayout();
            } else if (mReportLogic instanceof PastLifeReportLogic) {
                mReportLogic.updateMaskLayout();
            } else if (mReportLogic instanceof GenderSwitchReportLogic) {
                mReportLogic.updateMaskLayout();
            } else if (mReportLogic instanceof FutureBabyReportLogic) {
                mReportLogic.updateMaskLayout();
            }
        }
    }

    private void preApplyImg(final Uri data, final String path) {
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (data != null) {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data);
                        if (bitmap != null && !bitmap.isRecycled()) {
                            String path = PATH_PHOTO + File.separator + System.currentTimeMillis() + ".jpg";
                            ImageHelper.saveBitmapToSdcard(path, bitmap);
                            mImageYous[0] = path;
                            isModel = FaceConstant.isModel(path);
                            mImgYou = bitmap;
                            mBaseFaceResultBean = null;
                        }
                    } else {
                        mImageYous[0] = path;
                        mImgYou = APKAssertImageLoader.with(getResources()).load(mImageYous[0]).get();
                        isModel = FaceConstant.isModel(path);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mReportLogic.updateImage(mImageYous[0]);
                            process();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 激励视频逻辑
     */
    private boolean mRewardAdLoading;
    private RewardAdManager mRewardAdManager;

    public RewardAdManager getRewardAdManager() {
        if (mRewardAdManager == null) {
            initAd();
        }
        return mRewardAdManager;
    }

    private void initAd() {
        mRewardAdManager = new RewardAdManager(this, AdKeyConstant.ADMOB_REWARDED_VIDEO,
                AdKeyConstant.UNITY_REWARDED_VIDEO, AdKeyConstant.REWARDED_VIDEO_ID);
        mRewardAdManager.setShowOverTimeMills(20000L);
        mRewardAdManager.setRewardListener(new RewardAdManager.RewardListener() {
            @Override
            public void onReward() {
                //激励完成，重走报告页逻辑
                onSubscribeSuccessEvent(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_ONE_TIME));

                mRewardAdLoading = false;
                DialogStatistic.adVideoUnlock(mWhere);
                isfromButton =false;
            }

            @Override
            public void onFaild() {

                if (mRewardAdLoading) {
                    mRewardAdLoading = false;

                    if (CommercializeSDK.TestUser.isTestUser()) {
                        //激励完成，重走报告页逻辑
                        onSubscribeSuccessEvent(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_ONE_TIME));
                    }
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.reward_ad_load_failed);
                        }
                    });
                }
            }

            @Override
            public void onTimeOut() {
                //超时按照激励处理
                onReward();
            }
        });

        //WiFi环境下，预加载广告视频
        if (NetworkUtils.isWifi() && !isVipByType()) {
            mRewardAdManager.loadRewardVideoAd();
        }
    }

    public void fakeScanReq() {
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource);
    }

    /**
     * model图，假扫描成功统计
     */
    public void fakeScanReqSucc() {
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_SUCCESS,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),
                StatisticsConstant.KEY_PIC_SOURCE, picSource,
                StatisticsConstant.KEY_REQ_TIME, "(0,4)");
    }

    public String getPicSource() {
        return picSource;
    }
}
